<template>
  <div class="user-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-card class="search-card">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="queryParams.username"
              placeholder="请输入用户名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input
              v-model="queryParams.mobile"
              placeholder="请输入手机号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="用户状态" clearable>
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    
    <!-- 操作按钮区域 -->
    <div class="action-container">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button icon="el-icon-edit" :disabled="single" @click="handleUpdate">修改</el-button>
      <el-button 
        type="danger" 
        icon="el-icon-delete" 
        :disabled="multiple" 
        @click="handleDelete"
      >删除</el-button>
      <el-button icon="el-icon-upload2" @click="handleImport">导入</el-button>
      <el-button icon="el-icon-download" @click="handleExport">导出</el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="userList"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="用户编号" align="center" prop="id" width="100" />
        <el-table-column label="用户名称" align="center" prop="username" :show-overflow-tooltip="true" />
        <el-table-column label="用户昵称" align="center" prop="nickname" :show-overflow-tooltip="true" />
        <el-table-column label="部门" align="center" prop="deptName" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
        <el-table-column label="状态" align="center" prop="status" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
        <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button 
              type="text" 
              icon="el-icon-delete" 
              @click="handleDelete(scope.row)"
            >删除</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleResetPwd(scope.row)">重置密码</el-dropdown-item>
                  <el-dropdown-item @click="handleAuthRole(scope.row)">分配角色</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    
    <!-- 用户表单对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-tree-select
            v-model="form.deptId"
            :data="deptOptions"
            :props="{ label: 'label', value: 'id' }"
            placeholder="请选择归属部门"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" maxlength="11" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!form.id">
          <el-input v-model="form.password" placeholder="请输入密码" type="password" />
        </el-form-item>
        <el-form-item label="用户角色" prop="roleIds">
          <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 加载状态
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 用户表格数据
const userList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 部门树选项
const deptOptions = ref([])
// 角色选项
const roleOptions = ref([])
// 日期范围
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  username: undefined,
  nickname: undefined,
  password: undefined,
  deptId: undefined,
  email: undefined,
  mobile: undefined,
  status: 1,
  roleIds: [],
  remark: undefined
})

// 表单校验
const rules = {
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度必须在2到20个字符之间', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '用户昵称不能为空', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 模拟数据
const mockUserList = [
  {
    id: 1,
    username: 'admin',
    nickname: '管理员',
    deptName: '研发部门',
    mobile: '13800138000',
    email: 'admin@example.com',
    status: 1,
    createTime: '2023-01-01 00:00:00'
  },
  {
    id: 2,
    username: 'test',
    nickname: '测试用户',
    deptName: '测试部门',
    mobile: '13800138001',
    email: 'test@example.com',
    status: 1,
    createTime: '2023-01-02 00:00:00'
  }
]

const mockDeptOptions = [
  {
    id: 1,
    label: '总公司',
    children: [
      {
        id: 2,
        label: '研发部门'
      },
      {
        id: 3,
        label: '测试部门'
      }
    ]
  }
]

const mockRoleOptions = [
  {
    id: 1,
    roleName: '超级管理员'
  },
  {
    id: 2,
    roleName: '普通用户'
  }
]

// 查询用户列表
const getList = () => {
  loading.value = true
  // 模拟接口请求
  setTimeout(() => {
    userList.value = mockUserList
    total.value = mockUserList.length
    loading.value = false
  }, 500)
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.username = undefined
  form.nickname = undefined
  form.password = undefined
  form.deptId = undefined
  form.email = undefined
  form.mobile = undefined
  form.status = 1
  form.roleIds = []
  form.remark = undefined
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryParams.username = undefined
  queryParams.mobile = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  roleOptions.value = mockRoleOptions
  deptOptions.value = mockDeptOptions
  open.value = true
  title.value = '添加用户'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const userId = row?.id || ids.value[0]
  // 模拟获取用户详情
  const userInfo = mockUserList.find(item => item.id === userId)
  if (userInfo) {
    Object.assign(form, userInfo)
    form.roleIds = [1] // 模拟角色ID
  }
  roleOptions.value = mockRoleOptions
  deptOptions.value = mockDeptOptions
  open.value = true
  title.value = '修改用户'
}

// 提交按钮
const submitForm = () => {
  // 模拟提交
  ElMessage.success(form.id ? '修改成功' : '新增成功')
  open.value = false
  getList()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 删除按钮操作
const handleDelete = (row) => {
  const userIds = row?.id ? [row.id] : ids.value
  
  ElMessageBox.confirm('确认删除已选中的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除
    ElMessage.success('删除成功')
    getList()
  }).catch(() => {})
}

// 用户状态修改
const handleStatusChange = (row) => {
  const text = row.status === 1 ? '启用' : '停用'
  ElMessageBox.confirm(`确认要${text}该用户吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟修改状态
    ElMessage.success(`${text}成功`)
  }).catch(() => {
    row.status = row.status === 1 ? 0 : 1
  })
}

// 重置密码
const handleResetPwd = (row) => {
  ElMessageBox.prompt('请输入新密码', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputValidator: (value) => {
      if (!value) {
        return '密码不能为空'
      }
      if (value.length < 6) {
        return '密码长度不能小于6位'
      }
      return true
    }
  }).then(({ value }) => {
    // 模拟重置密码
    ElMessage.success('密码重置成功')
  }).catch(() => {})
}

// 分配角色
const handleAuthRole = (row) => {
  ElMessage.info('角色分配功能开发中...')
}

// 导入用户
const handleImport = () => {
  ElMessage.info('用户导入功能开发中...')
}

// 导出用户
const handleExport = () => {
  ElMessage.info('用户导出功能开发中...')
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-container {
  padding: 0;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.action-container {
  margin-bottom: 20px;
}

.table-card {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.05);
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
  margin-left: 8px;
}
</style> 